﻿Imports System.Data.OleDb

Public Class AquariumList
    Inherits System.Web.UI.Page

    ' TODO: Create special base page for listing content

    Protected ReadOnly Property DefaultOrder() As OrderCriterion
        Get
            Return New OrderCriterion("Title")
        End Get
    End Property

    Protected ReadOnly Property DefaultFilter() As FilterCriterion
        Get
            Return New FilterCriterion("Title", "")
        End Get
    End Property

    Protected Property OrderBy() As OrderCriterion
        Get
            If ViewState("OrderBy") Is Nothing Then
                ViewState("OrderBy") = DefaultOrder
            End If
            Return ViewState("OrderBy")
        End Get
        Set(value As OrderCriterion)
            ViewState("OrderBy") = value
        End Set
    End Property

    Protected Property FilterBy() As FilterCriterion
        Get
            If ViewState("FilterBy") Is Nothing Then
                ViewState("FilterBy") = DefaultFilter
            End If
            Return ViewState("FilterBy")
        End Get
        Set(value As FilterCriterion)
            ViewState("FilterBy") = value
        End Set
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            ResetFilter()
            UpdateDataSource()
        End If
    End Sub

    Protected Sub aquariumListGrid_Sorting(sender As Object, e As GridViewSortEventArgs) Handles aquariumListGrid.Sorting
        If e.SortExpression = OrderBy.Expression Then
            OrderBy.ToggleDirection()
        Else
            OrderBy = New OrderCriterion(e.SortExpression)
        End If
        UpdateDataSource()
    End Sub

    Protected Sub UpdateDataSource()
        Dim gateway As New AquariumGateway()
        If String.IsNullOrWhiteSpace(FilterBy.Value) Then
            aquariumListGrid.DataSource = gateway.FindAll(OrderBy)
        Else
            aquariumListGrid.DataSource = gateway.FindWhere(FilterBy, OrderBy)
        End If
        aquariumListGrid.DataBind()
    End Sub

    Protected Sub criterionTxt_TextChanged(sender As Object, e As EventArgs) Handles criterionTxt.TextChanged
        UpdateFilter()
        UpdateDataSource()
    End Sub

    Protected Sub searchBtn_Click(sender As Object, e As EventArgs) Handles searchBtn.Click
        UpdateFilter()
        UpdateDataSource()
    End Sub

    Protected Sub resetBtn_Click(sender As Object, e As EventArgs) Handles resetBtn.Click
        ResetFilter()
        UpdateDataSource()
    End Sub

    Protected Sub UpdateFilter()
        FilterBy = New FilterCriterion(criterionTypeDdl.SelectedValue, criterionTxt.Text)
    End Sub

    Protected Sub ResetFilter()
        FilterBy = Nothing
        criterionTypeDdl.SelectedValue = FilterBy.Column
        criterionTxt.Text = FilterBy.Value
    End Sub

End Class